package bizsocket.sample.j2se.slice;
/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import bizsocket.base.JSONRequestConverter;
import bizsocket.base.JSONResponseConverter;
import bizsocket.core.*;
import bizsocket.rx1.BizSocketRxSupport;
import bizsocket.sample.j2se.LogUtil;
import bizsocket.sample.j2se.ResourceTable;
import bizsocket.sample.j2se.SampleClient;
import bizsocket.sample.j2se.SampleServer;
import bizsocket.sample.j2se.common.OrderListSerialContext;
import bizsocket.sample.j2se.common.SampleBizPacketValidator;
import bizsocket.sample.j2se.common.SampleCmd;
import bizsocket.sample.j2se.common.SampleService;
import bizsocket.sample.rx2.LoggerUtil;
import bizsocket.tcp.Packet;
import bizsocket.tcp.Request;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.TextAlignment;
import ohos.agp.utils.TextTool;
import ohos.agp.window.dialog.ToastDialog;
import okio.ByteString;
import org.json.JSONException;
import org.json.JSONObject;
import rx.Subscriber;

import javax.net.ssl.SSLServerSocket;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

public class MainAbilitySlice extends AbilitySlice {

    private boolean duanxianconnect = true;
    private boolean oneask = true;
    private boolean notice = true;
    private boolean hebingask = true;
    private boolean divided = true;
    private boolean cache = true;
    private boolean lanjieqi = true;
    private boolean isOpenServer = false;
    private boolean isSendAsk = false;

    private TextField productid;
    private TextField isJuan;
    private TextField type;
    private TextField sl;
    private TextField host;
    private int i = 0;
    public boolean isSetIsClose() {
        return setIsClose;
    }

    public  void setSetIsClose(boolean setIsClose) {
        setIsClose = setIsClose;
    }

    private boolean setIsClose =false;


    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    private int port;
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        setPort(9103);
        setSetIsClose(true);
        productid = (TextField) findComponentById(ResourceTable.Id_productid);
        isJuan = (TextField) findComponentById(ResourceTable.Id_isJuan);
        type = (TextField) findComponentById(ResourceTable.Id_type);
        sl = (TextField) findComponentById(ResourceTable.Id_sl);
        host = (TextField) findComponentById(ResourceTable.Id_socketip);
        findComponentById(ResourceTable.Id_open).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (!isOpenServer) {
                    i = 1;
                    isOpenServer = true;
                    toast("开启RX服务器成功");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            setSocketServer();
                        }
                    }).start();
                } else {
                    if (i == 1) {
                        toast("rx服务正在运行，不能重复开启");
                    } else {
                        toast("rx2服务正在运行，不能重复开启");
                    }
                }
            }
        });
        findComponentById(ResourceTable.Id_close).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (TextTool.isNullOrEmpty(productid.getText().toString())) {
                    toast("productid不能为空");
                    return;
                } else if (TextTool.isNullOrEmpty(isJuan.getText().toString())) {
                    toast("isJuan不能为空");
                    return;
                } else if (TextTool.isNullOrEmpty(type.getText().toString())) {
                    toast("type不能为空");
                    return;
                } else if (TextTool.isNullOrEmpty(sl.getText().toString())) {
                    toast("sl不能为空");
                    return;
                }
                if (TextTool.isNullOrEmpty(host.getText().toString())) {
                    toast("host不能为空");
                    return;
                }

                if (!isSendAsk) {
                    isSendAsk = true;
                    if (!oneask) {
                        toast("您已关闭了一对一请求，请开启一对一请求");
                        return;
                    }
                    if (divided) {
                        LoggerUtil.i("包分片处理---包分片处理已开启，正在进行处理分发请求");
                        LoggerUtil.i("包分片处理---分发请求中");
                    } else {
                        LoggerUtil.i("包分片处理---包分片处理已关闭");
                    }
                    toast("开始发送请求");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            setSocket();
                        }
                    }).start();
                } else {
                    if (i == 1) {
                        toast("RX服务请求已发送，不能重复发送");
                    } else {
                        toast("RX2服务请求已发送，不能重复发送");
                    }
                }
            }
        });

        findComponentById(ResourceTable.Id_open_rx).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (!isOpenServer) {
                    isOpenServer = true;
                    toast("开启RX2服务器成功");
                    i = 2;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            openserver();
                        }
                    }).start();
                } else {
                    if (i == 1) {
                        toast("rx服务正在运行，不能重复开启");
                    } else {
                        toast("rx2服务正在运行，不能重复开启");
                    }
                }
            }
        });
        findComponentById(ResourceTable.Id_close_rx).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                if (TextTool.isNullOrEmpty(productid.getText().toString())) {
                    toast("productid不能为空");
                    return;
                } else if (TextTool.isNullOrEmpty(isJuan.getText().toString())) {
                    toast("isJuan不能为空");
                    return;

                } else if (TextTool.isNullOrEmpty(type.getText().toString())) {
                    toast("type不能为空");
                    return;
                } else if (TextTool.isNullOrEmpty(sl.getText().toString())) {
                    toast("sl不能为空");
                    return;
                }
                if (TextTool.isNullOrEmpty(host.getText().toString())) {
                    toast("host不能为空");
                    return;
                }
                if (!isSendAsk) {
                    isSendAsk = true;
                    if (!oneask) {
                        toast("您已关闭了一对一请求，请开启一对一请求");
                        return;
                    }
                    toast("开始发送请求");
                    if (divided) {
                        LoggerUtil.i("包分片处理---包分片处理已开启，正在进行处理分发请求");
                        LoggerUtil.i("包分片处理---分发请求中");
                    } else {
                        LoggerUtil.i("包分片处理---包分片处理已关闭");
                    }
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            sendRx();
                        }
                    }).start();
                } else {
                    if (i == 1) {
                        toast("RX服务请求已发送，不能重复发送");
                    } else {
                        toast("RX2服务请求已发送，不能重复发送");
                    }
                }
            }
        });

        findComponentById(ResourceTable.Id_connect_open).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                toast("开启断线重连");
                duanxianconnect = true;
            }
        });
        findComponentById(ResourceTable.Id_connect_close).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                toast("关闭断线重连");
                duanxianconnect = false;
            }
        });

        findComponentById(ResourceTable.Id_one_open).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                toast("开启一对一请求");
                oneask = true;
            }
        });
        findComponentById(ResourceTable.Id_one_close).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                toast("关闭一对一请求");
                oneask = false;
            }
        });

        findComponentById(ResourceTable.Id_notice_open).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                toast("开启通知和粘性通知");
                notice = true;
            }
        });
        findComponentById(ResourceTable.Id_notice_close).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                toast("关闭通知和粘性通知");
                notice = false;
            }
        });
        findComponentById(ResourceTable.Id_hebing_open).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                toast("开启串行请求合并");
                hebingask = true;
            }
        });
        findComponentById(ResourceTable.Id_hebing_close).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                toast("关闭串行请求合并");
                hebingask = false;
            }
        });

        findComponentById(ResourceTable.Id_divide_open).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                toast("开启包分片处理OhosFragmentRequestQueue");
                LoggerUtil.i("包分片处理---启动OhosFragmentRequestQueue，发起不同界面消息队列进行socket分发");

                divided = true;
            }
        });
        findComponentById(ResourceTable.Id_divide_close).setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                toast("关闭包分片处理OhosFragmentRequestQueue");
                LoggerUtil.i("包分片处理---关闭OhosFragmentRequestQueue");
                divided = false;
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    private void setSocketServer() {
        SSLServerSocket serverSocket = null;
        try {
            LoggerUtil.i("sssssocket--->" + "123");

            serverSocket = new SSLServerSocket(getPort()) {
                @Override
                public String[] getEnabledCipherSuites() {
                    return new String[0];
                }

                @Override
                public void setEnabledCipherSuites(String[] strings) {

                }

                @Override
                public String[] getSupportedCipherSuites() {
                    return new String[0];
                }

                @Override
                public String[] getSupportedProtocols() {
                    return new String[0];
                }

                @Override
                public String[] getEnabledProtocols() {
                    return new String[0];
                }

                @Override
                public void setEnabledProtocols(String[] strings) {

                }

                @Override
                public void setNeedClientAuth(boolean b) {

                }

                @Override
                public boolean getNeedClientAuth() {
                    return false;
                }

                @Override
                public void setWantClientAuth(boolean b) {

                }

                @Override
                public boolean getWantClientAuth() {
                    return false;
                }

                @Override
                public void setUseClientMode(boolean b) {

                }

                @Override
                public boolean getUseClientMode() {
                    return false;
                }

                @Override
                public void setEnableSessionCreation(boolean b) {

                }

                @Override
                public boolean getEnableSessionCreation() {
                    return false;
                }
            };
        } catch (IOException e) {
            LoggerUtil.i("sssssocket--->" + "IOException");

            e.fillInStackTrace();
        }

        new SampleServer.QuoteThread().start();
        boolean flag = true;
        if (isSetIsClose()) {
            LoggerUtil.i("sssssocket--->" + flag);
            Socket socket = null;
            try {
                socket = serverSocket.accept();
            } catch (IOException e) {
                LoggerUtil.i("sssssocket--->" + "IOException");
                e.fillInStackTrace();
            }
            LoggerUtil.i("sssssocket--->" + "ConnectThread");
            SampleServer.ConnectThread connectThread = new SampleServer.ConnectThread(socket);
            connectThread.start();
        }
    }

    private void setSocket() {

        SampleClient client = new SampleClient(new Configuration.Builder()
                .host(host.getText().toString())
                .port(getPort())
                .readTimeout(TimeUnit.SECONDS, 30)
                .heartbeat(60)
                .build());
        //增加串行数据的处理(把两个命令返回的数据进行合并)
        if (hebingask) {
            LoggerUtil.i("开启了串行请求合并");
            client.addSerialSignal(new SerialSignal(OrderListSerialContext.class, SampleCmd.QUERY_ORDER_LIST.getValue(),
                    new int[]{SampleCmd.QUERY_ORDER_LIST.getValue(), SampleCmd.QUERY_ORDER_TYPE.getValue()}));
        } else {
            LoggerUtil.i("关闭了串行请求合并");

        }
        //如果需要把
        client.getOne2ManyNotifyRouter().addStickyCmd(SampleCmd.NOTIFY_PRICE.getValue(), new SampleBizPacketValidator());

        client.getInterceptorChain().addInterceptor(new Interceptor() {
            @Override
            public boolean postRequestHandle(RequestContext context) throws Exception {
                LoggerUtil.i("sss--1->" + "发现一个请求postRequestHandle: " + context);
                LogUtil.debug("hilogggg", "context");
                return false;
            }

            @Override
            public boolean postResponseHandle(int command, Packet responsePacket) throws Exception {
                LoggerUtil.i("sss--2->" + "收到一个包postResponseHandle: " + responsePacket);
                return false;
            }
        });

        //创建rxjava请求环境(类似于retrofit)
        BizSocketRxSupport rxSupport = new BizSocketRxSupport.Builder()
                .requestConverter(new JSONRequestConverter())
                .responseConverter(new JSONResponseConverter())
                .bizSocket(client)
                .build();
        SampleService service = rxSupport.create(SampleService.class);

        try {
            //连接
            client.connect();

            //启动断线重连
            if (duanxianconnect) {

                client.getSocketConnection().bindReconnectionManager();
            } else {
                LoggerUtil.i("关闭断线重连。。。closeconnect()");
            }
            //开启心跳
            client.getSocketConnection().startHeartBeat();
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        //注册通知
        if (notice) {
            bizsocket.tcp.LoggerUtil.i("开启通知和粘性通知。。。notice()");
            client.subscribe(client, SampleCmd.NOTIFY_PRICE.getValue(), new ResponseHandler() {
                @Override
                public void sendSuccessMessage(int command, ByteString requestBody, Packet responsePacket) {
                    LoggerUtil.i("sss--3->" + "cmd: " + command + " ,requestBody: " + requestBody + " responsePacket: " + responsePacket);
                }

                @Override
                public void sendFailureMessage(int command, Throwable error) {
                    LoggerUtil.i("sss--4->" + command + " ,err: " + error);
                }
            });
        } else {
            bizsocket.tcp.LoggerUtil.i("关闭通知和粘性通知。。。notice()");
        }
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("productId", productid.getText().toString());
        map.put("isJuan", isJuan.getText().toString());
        map.put("type", type.getText().toString());
        map.put("sl", sl.getText().toString());
        LoggerUtil.i("一对一请求---一对一请求发送--》" + LogUtil.mapToString(map));

        String json = "{\"productId\" : \"1\",\"isJuan\" : \"0\",\"type\" : \"2\",\"sl\" : \"1\"}";
//        LoggerUtil.i("一对一请求---一对一请求发送--》" + json);

        client.request(new Request.Builder().command(SampleCmd.CREATE_ORDER.getValue()).utf8body(LogUtil.mapToString(map)).build(), new ResponseHandler() {
            @Override
            public void sendSuccessMessage(int command, ByteString requestBody, Packet responsePacket) {
                LoggerUtil.i("sss--5->" + "cmd: " + command + " ,requestBody: " + requestBody + " attach: " + " responsePacket: " + responsePacket);
            }

            @Override
            public void sendFailureMessage(int command, Throwable error) {
                LoggerUtil.i("sss--6->" + command + " ,err: " + error);
            }
        });


        JSONObject params = new JSONObject();
        try {
            params.put("pageSize", "10000");
        } catch (JSONException e) {
            e.fillInStackTrace();
        }

        service.queryOrderList(params).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
                LoggerUtil.i("sss--17->" + "rx response: " + "onCompleted");

            }

            @Override
            public void onError(Throwable e) {
                LoggerUtil.i("sss--17->" + "rx response: " + e.getMessage());

            }

            @Override
            public void onNext(JSONObject jsonObject) {
                LoggerUtil.i("sss--7->" + "rx response: " + jsonObject);
            }
        });

//        if (!productid.getText().toString().equals("1") && !isJuan.getText().toString().equals("0") && !type.getText().toString().equals("2") && !sl.getText().toString().equals("1"))
//        {
//            Map<String,String> map1 = new HashMap<String, String>();
//            map1.put("code","-1");
//            map1.put("msg","产品类型不正确");
//            LoggerUtil.i("Packet:" + LogUtil.mapToString(map1));
//        }

        while (true) {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.fillInStackTrace();
            }
        }


    }

    private void sendRx() {

        bizsocket.sample.rx2.j2se.SampleClient client = new bizsocket.sample.rx2.j2se.SampleClient(new Configuration.Builder()
                .host(host.getText().toString())
                .port(getPort())
                .readTimeout(TimeUnit.SECONDS, 30)
                .heartbeat(60)
                .build());

        //增加串行数据的处理(把两个命令返回的数据进行合并)
        if (hebingask) {
            LoggerUtil.i("开启了串行请求合并");
            client.addSerialSignal(new SerialSignal(bizsocket.sample.rx2.j2se.common.OrderListSerialContext.class, bizsocket.sample.rx2.j2se.common.SampleCmd.QUERY_ORDER_LIST.getValue(),
                    new int[]{bizsocket.sample.rx2.j2se.common.SampleCmd.QUERY_ORDER_LIST.getValue(), bizsocket.sample.rx2.j2se.common.SampleCmd.QUERY_ORDER_TYPE.getValue()}));
        } else {
            LoggerUtil.i("关闭了串行请求合并");
        }
        //如果需要把
        client.getOne2ManyNotifyRouter().addStickyCmd(bizsocket.sample.rx2.j2se.common.SampleCmd.NOTIFY_PRICE.getValue(), new bizsocket.sample.rx2.j2se.common.SampleBizPacketValidator());

        client.getInterceptorChain().addInterceptor(new Interceptor() {
            @Override
            public boolean postRequestHandle(RequestContext context) throws Exception {
                LoggerUtil.i("发现一个请求postRequestHandle: " + context);
                return false;
            }

            @Override
            public boolean postResponseHandle(int command, Packet responsePacket) throws Exception {
                LoggerUtil.i("收到一个包postResponseHandle: " + responsePacket);
                return false;
            }
        });

        //创建rxjava请求环境(类似于retrofit)
        bizsocket.rx2.BizSocketRxSupport rxSupport = new bizsocket.rx2.BizSocketRxSupport.Builder()
                .requestConverter(new JSONRequestConverter())
                .responseConverter(new JSONResponseConverter())
                .bizSocket(client)
                .build();
        bizsocket.sample.rx2.j2se.common.SampleService service = rxSupport.create(bizsocket.sample.rx2.j2se.common.SampleService.class);

        try {
            //连接
            client.connect();
            //启动断线重连
            if (duanxianconnect) {
                client.getSocketConnection().bindReconnectionManager();
            } else {
                bizsocket.tcp.LoggerUtil.i("关闭断线重连。。。closeconnect()");

            }
            //开启心跳
            client.getSocketConnection().startHeartBeat();
        } catch (Exception e) {
            e.fillInStackTrace();
        }

        //注册通知
        if (notice) {
            bizsocket.tcp.LoggerUtil.i("开启通知和粘性通知。。。notice()");
            client.subscribe(client, bizsocket.sample.rx2.j2se.common.SampleCmd.NOTIFY_PRICE.getValue(), new ResponseHandler() {
                @Override
                public void sendSuccessMessage(int command, ByteString requestBody, Packet responsePacket) {
                    LoggerUtil.i("cmd: " + command + " ,requestBody: " + requestBody + " responsePacket: " + responsePacket);
                }

                @Override
                public void sendFailureMessage(int command, Throwable error) {
                    LoggerUtil.i(command + " ,err: " + error);
                }
            });
        } else {
            bizsocket.tcp.LoggerUtil.i("关闭通知和粘性通知。。。notice()");

        }
        String json = "{\"productId\" : \"1\",\"isJuan\" : \"0\",\"type\" : \"2\",\"sl\" : \"1\"}";
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("productId", productid.getText().toString());
        map.put("isJuan", isJuan.getText().toString());
        map.put("type", type.getText().toString());
        map.put("sl", sl.getText().toString());
        LoggerUtil.i("一对一请求---一对一请求发送--》" + LogUtil.mapToString(map));
//        if (!productid.getText().toString().equals("1") && !isJuan.getText().toString().equals("0") && !type.getText().toString().equals("2") && !sl.getText().toString().equals("1")) {
//            Map<String,String> map1 = new HashMap<String, String>();
//            map1.put("code","-1");
//            map1.put("msg","产品类型不正确");
//            LoggerUtil.i("Packet:" + LogUtil.mapToString(map1));
//        }

        client.request(new Request.Builder().command(bizsocket.sample.rx2.j2se.common.SampleCmd.CREATE_ORDER.getValue()).utf8body(LogUtil.mapToString(map)).build(), new ResponseHandler() {
            @Override
            public void sendSuccessMessage(int command, ByteString requestBody, Packet responsePacket) {
                LoggerUtil.i("cmd: " + command + " ,requestBody: " + requestBody + " attach: " + " responsePacket: " + responsePacket);
            }

            @Override
            public void sendFailureMessage(int command, Throwable error) {
                LoggerUtil.i(command + " ,err: " + error);
            }
        });


        JSONObject params = new JSONObject();
        try {
            params.put("pageSize", "10000");
        } catch (JSONException e) {
            e.fillInStackTrace();
        }

        service.queryOrderList(params).subscribe(new Observer<JSONObject>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(JSONObject jsonObject) {
                LoggerUtil.i("rx response: " + jsonObject);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });

        while (true) {
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.fillInStackTrace();
            }
        }

    }

    private void openserver() {
        SSLServerSocket serverSocket = null;
        try {
            serverSocket = new SSLServerSocket(getPort()) {
                @Override
                public String[] getEnabledCipherSuites() {
                    return new String[0];
                }

                @Override
                public void setEnabledCipherSuites(String[] strings) {

                }

                @Override
                public String[] getSupportedCipherSuites() {
                    return new String[0];
                }

                @Override
                public String[] getSupportedProtocols() {
                    return new String[0];
                }

                @Override
                public String[] getEnabledProtocols() {
                    return new String[0];
                }

                @Override
                public void setEnabledProtocols(String[] strings) {

                }

                @Override
                public void setNeedClientAuth(boolean b) {

                }

                @Override
                public boolean getNeedClientAuth() {
                    return false;
                }

                @Override
                public void setWantClientAuth(boolean b) {

                }

                @Override
                public boolean getWantClientAuth() {
                    return false;
                }

                @Override
                public void setUseClientMode(boolean b) {

                }

                @Override
                public boolean getUseClientMode() {
                    return false;
                }

                @Override
                public void setEnableSessionCreation(boolean b) {

                }

                @Override
                public boolean getEnableSessionCreation() {
                    return false;
                }
            };
        } catch (IOException e) {
            e.fillInStackTrace();
        }

        new bizsocket.sample.rx2.j2se.SampleServer.QuoteThread().start();
        boolean flag = true;
        if (isSetIsClose()) {
            Socket socket = null;
            try {
                socket = serverSocket.accept();
            } catch (IOException e) {
                e.fillInStackTrace();
            }
            bizsocket.sample.rx2.j2se.SampleServer.ConnectThread connectThread = new bizsocket.sample.rx2.j2se.SampleServer.ConnectThread(socket);
            connectThread.start();
        }
    }

    private static final int MAX_LINE = 2;
    private static final int OFFSET_Y = 60;

    private void toast(String string) {
        try {
            DirectionalLayout toastLayout = (DirectionalLayout) LayoutScatter.getInstance(MainAbilitySlice.this)
                    .parse(ResourceTable.Layout_layout_toast, null, false);
            Text text = (Text) toastLayout.findComponentById(ResourceTable.Id_msg_toast);
            text.setText(string);
            text.setTextAlignment(TextAlignment.LEFT);
            text.setMultipleLine(true);
            text.setMaxTextLines(MAX_LINE);
            text.setTruncationMode(Text.TruncationMode.ELLIPSIS_AT_END);
            new ToastDialog(MainAbilitySlice.this)
                    .setComponent(toastLayout)
                    .setSize(DirectionalLayout.LayoutConfig.MATCH_CONTENT, DirectionalLayout.LayoutConfig.MATCH_CONTENT)
                    .setAlignment(LayoutAlignment.BOTTOM | LayoutAlignment.HORIZONTAL_CENTER)
                    .setOffset(0, OFFSET_Y)
                    .show();
        } catch (Exception e) {
            e.fillInStackTrace();
        }

    }
}

